<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="菜单名称" prop="menuName">
                <el-input
                        v-model="queryParams.menuName"
                        placeholder="请输入菜单名称"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="状态 " prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态 " clearable>
                    <el-option
                            v-for="dict in sys_normal_disable"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['system:menu:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="info"
                        plain
                        icon="Sort"
                        @click="toggleExpandAll"
                >展开/折叠
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getTreeList"></right-toolbar>
        </el-row>

        <el-table
                v-if="refreshTable"
                v-loading="loading"
                :data="menuList"
                :row-key="row => { return row.id.toString() }"
                :default-expand-all="isExpandAll"
                :expand-row-keys="expandRowKeys"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                :cell-style="tableCellStyle"
        >
            <el-table-column label="菜单名称" align="left" min-width="120" prop="menuName" show-overflow-tooltip/>
            <el-table-column label="菜单图标" align="center" prop="icon">
                <template #default="scope">
                    <el-icon size="15px">
                        <component :is="scope.row.icon"/>
                    </el-icon>
                </template>
            </el-table-column>
            <el-table-column label="排序" align="center" prop="orderNum"/>
            <el-table-column label="权限标识" align="center" prop="perms" show-overflow-tooltip/>
            <el-table-column label="组件路径" align="center" prop="component" show-overflow-tooltip/>
            <el-table-column label="状态 " align="center" prop="status">
                <template #default="scope">
                    <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
            <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button
                            type="primary"
                            text
                            icon="Edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['system:menu:edit']"
                    >修改
                    </el-button>
                    <el-button
                            type="primary"
                            text
                            icon="Plus"
                            @click="handleAdd(scope.row)"
                            v-hasPermi="['system:menu:add']"
                    >新增
                    </el-button>
                    <el-button
                            type="danger"
                            text
                            icon="Delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['system:menu:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加或修改菜单权限对话框 -->
        <el-dialog :title="title" v-model="open" width="700px" append-to-body>
            <el-form v-if="open" ref="menuRef" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="10">
                    <el-col :span="24">
                        <el-form-item label="父级菜单" prop="parentId">
                            <el-tree-select
                                    style="width: 100%;"
                                    v-model="form.parentId"
                                    :data="menuOptions"
                                    :props="{ value: 'id', label: 'label', children: 'children' }"
                                    value-key="id"
                                    placeholder="请选择父级菜单"
                                    check-strictly
                            >
                                <template #default="{data: {label, children}}">
                                    {{ label }}<span v-if="children">({{children.length}})</span>
                                </template>
                            </el-tree-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="菜单类型" prop="menuType">
                            <el-radio-group v-model="form.menuType">
                                <el-radio
                                        v-for="dict in sys_menu_type"
                                        :key="dict.value"
                                        :value="dict.value"
                                >{{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="form.menuType !== proxy.$constant.TYPE_BUTTON">
                        <el-form-item label="菜单图标" prop="icon">
                            <el-select style="width: 100%;" v-model="form.icon" filterable placeholder="选择图标">
                                <template #prefix v-if="form.icon">
                                    <el-icon size="1rem">
                                        <component :is="form.icon"/>
                                    </el-icon>
                                </template>
                                <template #prefix v-else>
                                    <el-icon size="1rem"><Search /></el-icon>
                                </template>
                                <el-option v-for="icon in iconList"
                                           :key="icon" :label="icon" :value="icon">
                                    <div style="display: flex;align-items: center;">
                                        <el-icon size="1.2rem">
                                            <component :is="icon"/>
                                        </el-icon>&nbsp;&nbsp;
                                        <span>{{ icon }}</span>
                                    </div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="菜单名称" prop="menuName">
                            <el-input v-model="form.menuName" placeholder="请输入菜单名称"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="显示顺序" prop="orderNum">
                            <el-input-number style="width: 100%;" v-model="form.orderNum" controls-position="right" placeholder="请输入显示顺序"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType !== proxy.$constant.TYPE_BUTTON">
                        <el-form-item label="路由地址" prop="path">
                            <template  #label>
                                <span>
                                    <el-tooltip effect="dark" content="访问的路由地址，如：`user`" placement="top">
                                        <el-icon><QuestionFilled /></el-icon>
                                    </el-tooltip>
                                    路由地址
                                </span>
                            </template>
                            <el-input v-model="form.path" placeholder="请输入路由地址"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType === proxy.$constant.TYPE_MENU">
                        <el-form-item label="组件路径" prop="component">
                            <template  #label>
                                <span>
                                    <el-tooltip effect="dark" content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                                        <el-icon><QuestionFilled /></el-icon>
                                    </el-tooltip>
                                    组件路径
                                </span>
                            </template>
                            <el-input v-model="form.component" placeholder="请输入组件路径"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType !== proxy.$constant.TYPE_DIR">
                        <el-form-item label="权限标识" prop="perms">
                            <template  #label>
                                <span>
                                    <el-tooltip effect="dark" content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)" placement="top">
                                        <el-icon><QuestionFilled /></el-icon>
                                    </el-tooltip>
                                    权限标识
                                </span>
                            </template>
                            <el-input v-model="form.perms" placeholder="请输入权限标识"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.menuType !== proxy.$constant.TYPE_BUTTON">
                        <el-form-item label="显示状态 " prop="visible">
                            <template  #label>
                                <span>
                                    <el-tooltip effect="dark" content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                                        <el-icon><QuestionFilled /></el-icon>
                                    </el-tooltip>
                                    显示状态
                                </span>
                            </template>
                            <el-radio-group v-model="form.visible">
                                <el-radio
                                        v-for="dict in sys_show_hide"
                                        :key="dict.value"
                                        :value="dict.value"
                                >{{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态 " prop="status">
                            <template  #label>
                                <span>
                                    <el-tooltip effect="dark" content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                                        <el-icon><QuestionFilled /></el-icon>
                                    </el-tooltip>
                                    状态
                                </span>
                            </template>
                            <el-radio-group v-model="form.status">
                                <el-radio
                                    v-for="dict in sys_normal_disable"
                                    :key="dict.value"
                                    :value="dict.value"
                                >{{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24" v-if="form.menuType !== proxy.$constant.TYPE_BUTTON">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Menu">
import {listTreeMenu, treeSelect, getMenu, delMenu, addMenu, updateMenu} from "@/api/system/menu";
import {getCurrentInstance, nextTick, reactive, ref, toRefs} from "vue";

const {proxy} = getCurrentInstance();
const {
    sys_menu_type,
    sys_normal_disable,
    sys_show_hide
} = proxy.initDict('sys_menu_type', 'sys_normal_disable', 'sys_show_hide');

const menuList = ref([]);
const menuOptions = ref([]);
const isExpandAll = ref(false);
const expandRowKeys = ref([]);
const refreshTable = ref(true);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");

const data = reactive({
    form: {},
    queryParams: {
        menuName: null,
        status: null
    },
    rules: {
        parentId: [
            {required: true, message: '请选择上级菜单', trigger: 'change'}
        ],
        menuType: [
            {required: true, message: '请选择菜单类型', trigger: 'change'}
        ],
        menuName: [
            {required: true, message: '请输入菜单名称', trigger: 'blur'}
        ],
        path: [
            {required: true, message: '请输入路由地址', trigger: 'blur'}
        ],
        orderNum: [
            {required: true, message: '请输入显示顺序', trigger: 'blur'}
        ],
        status: [
            {required: true, message: '请选择状态', trigger: 'change'}
        ],
        visible:[
            {required: true, message: '请选择显示状态', trigger: 'change'}
        ]
    }
});

const {queryParams, form, rules} = toRefs(data);

//图标列表
const iconList = proxy.$Icons;

getTreeList();

/** 查询菜单权限树列表 */
function getTreeList() {
    loading.value = true;
    listTreeMenu(queryParams.value).then(response => {
        menuList.value = response.data;
        expandRowKeys.value = response.data.map(m => m.id.toString());
        loading.value = false;
    });
}

/** 查询菜单权限下拉树结构 */
function getTreeSelect() {
    treeSelect().then(response => {
        menuOptions.value = [];
        const data = {id: 0, label: '主类目', children: []};
        data.children = response.data;
        menuOptions.value.push(data);
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        createBy: null,
        createTime: null,
        deleteFlag: null,
        remark: null,
        updateBy: null,
        updateTime: null,
        component: null,
        icon: null,
        menuName: null,
        menuType: "D",
        orderNum: 0,
        parentId: null,
        path: null,
        perms: null,
        status: "0",
        visible: "0"
    };
    proxy.resetForm("menuRef");
}

//单元格的 style 的回调方法
function tableCellStyle({row, column, rowIndex, columnIndex}) {
    if (column.property === 'menuName'){
        if (row.menuType === proxy.$constant.TYPE_DIR) { //目录
            return {
                "font-size": "15px",
                "font-weight": "bold"
            }
        }else if (row.menuType === proxy.$constant.TYPE_MENU) { //菜单
            return {
                "font-weight": "bold"
            }
        }
    }
}

/** 搜索按钮操作 */
function handleQuery() {
    getTreeList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
    reset();
    getTreeSelect();
    if (row != null && row.id) {
        form.value.parentId = row.id;
    } else {
        form.value.parentId = 0;
    }
    open.value = true;
    title.value = "添加菜单权限";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
        refreshTable.value = true;
    });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
    reset();
    await getTreeSelect();
    if (row != null) {
        form.value.parentId = row.id;
    }
    getMenu(row.id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改菜单权限";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["menuRef"].validate(valid => {
        if (valid) {
            if (form.value.id != null) {
                updateMenu(form.value).then(response => {
                    proxy.$message.success("修改成功");
                    open.value = false;
                    getTreeList();
                });
            } else {
                addMenu(form.value).then(response => {
                    proxy.$message.success("新增成功");
                    open.value = false;
                    getTreeList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    proxy.$messageBox.confirm('是否确认删除菜单权限编号为"' + row.id + '"的数据项？').then(function () {
        return delMenu(row.id);
    }).then(() => {
        getTreeList();
        proxy.$message.success("删除成功");
    }).catch(() => {
    });
}

</script>
